<script setup lang="ts">
import { ref, computed, onBeforeUnmount, compile } from 'vue'
import CustomModal from './components/CustomModal.vue'
import { onHide, onLoad, onUnload, onShow } from '@dcloudio/uni-app'
import Map from './auto-map.vue'
import {
  startServiceAPI,
  updateDriverLocationAPI,
  getDriverSetAPI,
  findNewOrderQueueDataAPI,
  stopServiceAPI,
  robNewOrderAPI,
  searchDriverCurrentOrderAPI,
  calculateDrivingLineAPI,
  startDriveAPI,
  updateOrderLocationToCacheAPI,
  driverArriveStartLocationAPI,
  updateDriverOrderLocationToCacheAPI,
  endDriverAPI,
} from '@/services/home'
const { safeAreaInsets } = uni.getSystemInfoSync()
import { useMemberStore, useDriverLocationCacheStore } from '@/stores'
import type { DeliveryTasksDTO, NewOrderDataVo, locationDataform } from '@/types/home'
import { getDictAllData } from '@/services/dict'
const { getUserInfo, getProfile } = useMemberStore()
const { getLocationData, addLocationData, clearLocationData } = useDriverLocationCacheStore()
// eslint-disable-next-line no-undef
const bmap = require('../../static/js/bmap-wx.min.js')
const BMapWX = bmap.BMapWX
//    这个地方是你在百度地图中申请的ak
var BMap = new BMapWX({ ak: 'hOtF9JR4wCD5SSQGKhddv4IsHildEpVF' })
const latitude = ref(0)
const longitude = ref(0)
const showModal = ref(false)

// 响应式数据
const markers = ref([] as any[])
const testPolyline: any[] = [
  {
    points: [
      {
        latitude: 39.925539,
        longitude: 116.279037,
      },
      {
        latitude: 39.925539,
        longitude: 116.520285,
      },
    ],
    color: '#FFCCFF',
    width: 7,
    dottedLine: true,
    arrowLine: true,
    borderColor: '#000000',
    borderWidth: 2,
  },
  {
    points: [
      {
        latitude: 39.938698,
        longitude: 116.275177,
      },
      {
        latitude: 39.966069,
        longitude: 116.289253,
      },
      {
        latitude: 39.944226,
        longitude: 116.306076,
      },
      {
        latitude: 39.966069,
        longitude: 116.322899,
      },
      {
        latitude: 39.938698,
        longitude: 116.336975,
      },
    ],
    color: '#CCFFFF',
    width: 5,
    dottedLine: false,
    arrowLine: true,
    borderColor: '#CC0000',
    borderWidth: 3,
  },
]
const polyline = ref([] as any[])
const loading = ref(false)

const handleConfirm = async () => {
  console.log('用户点击确认')
  const orderId = (orders.value.find((item: any) => item.checked) as any)?.orderId as string
  if (!orderId) {
    uni.showToast({
      title: '请选择订单',
      icon: 'none',
    })
    return
  }
  const res = await robNewOrderAPI(getUserInfo()?.id, orderId)
  if (res.data) {
    uni.showToast({
      title: '抢单成功',
      icon: 'success',
    })
    clearTimer()
    runing.value = false
    // 关闭弹出框
    showModal.value = false

    searchDriverCurrentOrderRequest()
  }
}

const handleCancel = () => {
  console.log('用户点击取消')
}

const handleClose = () => {
  console.log('弹窗已关闭')
}

const timer = ref(null as any)
const orders = ref([] as NewOrderDataVo[])
const timerRequest = async () => {
  const res = await findNewOrderQueueDataAPI(getUserInfo()?.id)
  if (res.data) {
    orders.value = res.data.map((item: any) => {
      if (checkedRecord.value.orderId === item.orderId) {
        return { ...item, ...checkedRecord.value }
      }
      return { ...item, checked: false }
    })
  }
}

const startTimer = () => {
  clearTimer()
  if (getUserInfo()?.id && getProfile()?.access_token) {
    timerRequest() // 立即执行一次
    timer.value = setInterval(timerRequest, 10000)
  }
}
onLoad(async (e: any) => {
  console.log('ceshi', e)

  // serviceStatusType.value = ((await getDictAllData('delivery_status_type')) as any[]).map(
  //   (item: any) => {
  //     return { value: Number(item.dictValue), text: item.dictLabel }
  //   },
  // )
})

const currentOrderData = ref({} as DeliveryTasksDTO)

const searchDriverCurrentOrderRequest = async () => {
  const res = await searchDriverCurrentOrderAPI(getUserInfo()?.id)
  currentOrderData.value = res.data

  if (res.data.isHasCurrentOrder) {
    if (currentOrderData.value.deliveryStatus === 2) {
      startDriverLocationUpdate()
    }

    if (currentOrderData.value.deliveryStatus === 7) {
      startLocationUpdate()
    }
    const { startPointLongitude, startPointLatitude, endPointLongitude, endPointLatitude } =
      currentOrderData.value

    uni.getLocation({
      type: 'gcj02', // 'wgs84'
      isHighAccuracy: true,
      geocode: true,
      success: async (res: any) => {
        res = { ...res, latitude: 38.466933, longitude: 112.786157 }
        latitude.value = res.latitude
        longitude.value = res.longitude
        const startPoint = { lat: latitude.value, lng: longitude.value, title: '起始点' }
        const pickupPoint = { lat: startPointLatitude, lng: startPointLongitude, title: '取货点' }
        const endPoint = { lat: endPointLatitude, lng: endPointLongitude, title: '终点' }
        await getRoutePath(startPoint, pickupPoint, endPoint)
      },
    })
  } else {
    uni.getLocation({
      type: 'gcj02', // 'wgs84'
      isHighAccuracy: true,
      geocode: true,
      success: async (res: any) => {
        res = { ...res, latitude: 38.466933, longitude: 112.786157 }
        latitude.value = res.latitude
        longitude.value = res.longitude
        includePoints.value = []
        polyline.value = []
        markers.value = []
      },
    })
  }
}
const getPolyline = (points: any[], isStart: boolean): any => {
  const formattedPoints = points.map((item: any) => ({
    longitude: item[0],
    latitude: item[1],
  }))

  return {
    points: formattedPoints,
    color: isStart ? '#FFCCFF' : '#CCFFFF',
    width: 5,
    dottedLine: false,
    arrowLine: true,
    borderColor: isStart ? '#f00' : '#CC0000',
    borderWidth: 3,
  }
}

const includePoints = ref([] as any[])
const getRoutePath = async (startPoint: any, pickupPoint: any, endPoint: any) => {
  includePoints.value = [
    {
      latitude: startPoint.lat,
      longitude: startPoint.lng,
    },
    {
      latitude: pickupPoint.lat,
      longitude: pickupPoint.lng,
    },
    {
      latitude: endPoint.lat,
      longitude: endPoint.lng,
    },
  ]
  const pickupRouter = await calculateDrivingLineAPI({
    startPointLongitude: startPoint.lng,
    startPointLatitude: startPoint.lat,
    endPointLongitude: pickupPoint.lng,
    endPointLatitude: pickupPoint.lat,
  })

  const endRouter = await calculateDrivingLineAPI({
    startPointLongitude: pickupPoint.lng,
    startPointLatitude: pickupPoint.lat,
    endPointLongitude: endPoint.lng,
    endPointLatitude: endPoint.lat,
  })

  polyline.value = [
    getPolyline(pickupRouter.data.polyline, true),
    getPolyline(endRouter.data.polyline.slice(1), false),
  ]

  // const a1 = [
  //   [112.746147, 38.404425],
  //   [112.746861, 38.404561],
  //   [112.747613, 38.404704],
  //   [112.747613, 38.404704],
  //   [112.747755, 38.404731],
  //   [112.747755, 38.404731],
  //   [112.747728, 38.404824],
  //   [112.747728, 38.404824],
  //   [112.747586, 38.404796],
  //   [112.747586, 38.404796],
  //   [112.746606, 38.404607],
  //   [112.746606, 38.404607],
  //   [112.746569, 38.40465],
  //   [112.746534, 38.404693],
  //   [112.746534, 38.404693],
  //   [112.746506, 38.404721],
  //   [112.746441, 38.404771],
  //   [112.746404, 38.4048],
  // ]

  // const a2 = [
  //   [112.746404, 38.4048],
  //   [112.746441, 38.404771],
  //   [112.746506, 38.404721],
  //   [112.746534, 38.404693],
  //   [112.746534, 38.404693],
  //   [112.746569, 38.40465],
  //   [112.746606, 38.404607],
  //   [112.746606, 38.404607],
  //   [112.745845, 38.404461],
  //   [112.745084, 38.404314],
  //   [112.745084, 38.404314],
  //   [112.744761, 38.404252],
  //   [112.744438, 38.40419],
  //   [112.744438, 38.40419],
  //   [112.744459, 38.404104],
  //   [112.744459, 38.404104],
  //   [112.74476, 38.404161],
  //   [112.74476, 38.404161],
  //   [112.745128, 38.404231],
  //   [112.745128, 38.404231],
  //   [112.746108, 38.404418],
  //   [112.746108, 38.404418],
  //   [112.746861, 38.404561],
  //   [112.747613, 38.404704],
  //   [112.747613, 38.404704],
  //   [112.747784, 38.40422],
  //   [112.747954, 38.403736],
  //   [112.747954, 38.403736],
  //   [112.748112, 38.403287],
  //   [112.748112, 38.403287],
  //   [112.748267, 38.402852],
  //   [112.748267, 38.402852],
  //   [112.74828, 38.402815],
  //   [112.74828, 38.402815],
  //   [112.748474, 38.402283],
  //   [112.748669, 38.40175],
  //   [112.748669, 38.40175],
  //   [112.749162, 38.400507],
  //   [112.749162, 38.400507],
  //   [112.748266, 38.400358],
  //   [112.748266, 38.400358],
  //   [112.74776, 38.400288],
  //   [112.74776, 38.400288],
  //   [112.746839, 38.400162],
  //   [112.746839, 38.400162],
  //   [112.746189, 38.400069],
  // ]

  // polyline.value = [getPolyline(a1, true), getPolyline(a2.slice(1), false)]

  markers.value = [startPoint, pickupPoint, endPoint].map((item: any, index: number) => ({
    title: item.title,
    address: item.title,
    alpha: 1,
    width: 30,
    height: 30,
    id: index,
    telephone: '',
    latitude: item.lat,
    longitude: item.lng,
    iconPath: index === 0 ? '../../static/imgs/derlivery.png' : '../../static/imgs/red_marker.png',
    iconTapPath:
      index === 0 ? '../../static/imgs/derlivery.png' : '../../static/imgs/red_marker.png',
    label: item.title,
    callout: {
      content: item.title,
      display: 'ALWAYS',
    },
  }))
}

const clearTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
    orders.value = []
  }
}

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  clearTimer()
})

const markertap = (info: any) => {
  console.log(info)
}

const loginHandler = () => {
  uni.navigateTo({
    url: '/pages/login/login',
  })
}
const runing = ref(false)

const acceptOrdersHandler = async () => {
  runing.value = true
  const driverId = getUserInfo()?.id
  if (driverId) {
    // 判断是否有配送设置，没有就提示创建配置
    const driverSet = await getDriverSetAPI(driverId)

    if (!driverSet.data) {
      uni.showToast({
        title: '请先创建配送设置',
        icon: 'none',
      })
      uni.navigateTo({
        url: '/pages/driver-set/driver-set',
      })
      return
    }
    await startServiceAPI(driverId)
    await updateDriverLocationAPI({
      driverId,
      latitude: latitude.value,
      longitude: longitude.value,
    })
    startTimer()
  } else {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
  }
}

const stopServiceHandler = async () => {
  const driverId = getUserInfo()?.id
  if (driverId) {
    await stopServiceAPI(driverId)
    clearTimer()
    runing.value = false
  }
}

const runningHandler = () => {
  // 模态弹窗
  uni.showModal({
    content: '是否继续等待？',
    success: (res) => {
      if (!res.confirm) {
        stopServiceHandler()
      }
    },
  })
}

const checkedRecord = ref({} as any)

const clickHandler = (item: any) => {
  const tag = !item.checked
  orders.value = orders.value.map((v: any) => {
    if (v.orderId === item.orderId) {
      v.checked = tag
      item.checked = tag
      checkedRecord.value = item
    } else {
      v.checked = false
    }
    return v
  })
}

/**
 * 开始服务
 */
const startserviceHandler = async () => {
  await startDriveAPI({
    userId: getUserInfo().id,
    orderId: currentOrderData.value?.orderId as number,
    driverId: currentOrderData.value?.driverId as number,
  })

  startLocationUpdate()

  // 刷新状态
  currentOrderData.value.deliveryStatus = 7
}
const startLocationUpdateRef = ref(null as any)
const startDriverLocationUpdateRef = ref(null as any)
const startLocationUpdate = () => {
  clearStartLocationTimer()
  const updateRequest = () => {
    uni.getLocation({
      type: 'gcj02', // 'wgs84'
      isHighAccuracy: true,
      geocode: true,
      success: async (res: any) => {
        res = { ...res, latitude: 38.476839, longitude: 112.794998 }
        const { latitude, longitude } = res
        // const [longitude, latitude] = [112.746606, 38.404607]
        markers.value = markers.value.map((marker: any) => {
          if (marker.id === 0) {
            // id=0是配送员
            return {
              ...marker,
              latitude,
              longitude,
            }
          }
          return marker
        })
        await updateOrderLocationToCacheAPI({
          orderId: currentOrderData.value?.orderId as number,
          latitude,
          longitude,
        })
      },
    })
  }

  updateRequest()
  startLocationUpdateRef.value = setInterval(updateRequest, 2 * 60 * 1000) // 每10秒执行一次
}

const clearStartLocationTimer = () => {
  if (startLocationUpdateRef.value) {
    clearInterval(startLocationUpdateRef.value)
    startLocationUpdateRef.value = null
  }
}
const clearDriverStartLocationTimer = () => {
  if (startDriverLocationUpdateRef.value) {
    clearInterval(startDriverLocationUpdateRef.value)
    startDriverLocationUpdateRef.value = null
  }
}

onShow(() => {
  // 查询当前订单状态
  searchDriverCurrentOrderRequest()
})

const lastUpdateLocationDataList = async () => {
  clearDriverStartLocationTimer()
  const locationDataList = getLocationData()
  if (locationDataList.length > 0) {
    await updateDriverOrderLocationToCacheAPI(locationDataList)
  }
}

onHide(() => {
  clearStartLocationTimer()
  lastUpdateLocationDataList()
})

onUnload(() => {
  clearStartLocationTimer()
  lastUpdateLocationDataList()
})

const startDriverLocationUpdate = () => {
  clearDriverStartLocationTimer()
  const updateDriverRequest = () => {
    uni.getLocation({
      type: 'gcj02', // 'wgs84'
      isHighAccuracy: true,
      geocode: true,
      success: async (res: any) => {
        res = { ...res, latitude: 38.466933, longitude: 112.786157 }
        // const { latitude, longitude } = res
        // const [longitude, latitude] = [112.74776, 38.400288]
        const [longitude, latitude] = [
          currentOrderData.value.endPointLongitude,
          currentOrderData.value.endPointLatitude,
        ]

        markers.value = markers.value.map((marker: any) => {
          if (marker.id === 0) {
            // id=0是配送员
            return {
              ...marker,
              latitude,
              longitude,
            }
          }
          return marker
        })

        // 缓存实时坐标
        addLocationData({
          orderId: currentOrderData.value?.orderId as number,
          latitude,
          longitude,
        })

        const locationDataList = getLocationData()
        if (locationDataList.length > 5) {
          await updateDriverOrderLocationToCacheAPI(locationDataList)
          clearLocationData()
        }
      },
    })
  }

  updateDriverRequest()
  startDriverLocationUpdateRef.value = setInterval(updateDriverRequest, 10 * 1000) // 每10秒执行一次
  // startDriverLocationUpdateRef.value = setInterval(updateDriverRequest, 2 * 60 * 1000) // 每10秒执行一次
}

const pickupHandler = () => {
  // 模态弹窗
  uni.showModal({
    content: '是否取货？',
    success: async (res) => {
      if (res.confirm) {
        const res = await driverArriveStartLocationAPI(
          currentOrderData.value?.orderId as number,
          currentOrderData.value?.driverId as number,
        )
        // 关闭到达起点前的位置上报
        clearStartLocationTimer()
        // todo
        currentOrderData.value.deliveryStatus = 2
        startDriverLocationUpdate()
      }
    },
  })
}
const okHandler = () => {
  uni.showModal({
    content: '是否确认送达结束任务？',
    success: async (res) => {
      if (res.confirm) {
        // 最后更新地址，停止配送地址上报
        clearStartLocationTimer()
        lastUpdateLocationDataList()
        await endDriverAPI({
          taskId: currentOrderData.value?.id as number,
          driverId: currentOrderData.value?.driverId as number,
        })
        // 结束服务
        polyline.value = []
        orders.value = []
        markers.value = []
        searchDriverCurrentOrderRequest()
      }
    },
  })
}
</script>

<template>
  <view class="index-page">
    <map
      class="map"
      id="map"
      style="width: 100%; height: 100%"
      :longitude="longitude"
      :latitude="latitude"
      :include-points="includePoints"
      :scale="14"
      :polyline="polyline"
      :markers="markers"
      @markertap="markertap"
    ></map>
    <view class="drawer">
      <template v-if="getUserInfo()?.id">
        <template v-if="currentOrderData?.isHasCurrentOrder">
          <view class="top">
            <view> 距离：{{ currentOrderData?.expectDistance }} </view>
            <view> 耗时：{{ currentOrderData?.expectDuration }} </view>
          </view>
          <view class="bottom">
            <view class="addres-info"> {{ currentOrderData?.endLocation }} </view>
          </view>
          <view class="btn" v-if="currentOrderData.deliveryStatus === 1">
            <view class="addres-info" @click="startserviceHandler"> 开始服务 </view>
          </view>
          <view class="btn" v-if="currentOrderData.deliveryStatus === 7">
            <view class="addres-info" @click="pickupHandler"> 是否已取货 </view>
          </view>
          <view class="btn" v-if="currentOrderData.deliveryStatus === 2">
            <view class="addres-info" @click="okHandler"> 是否送达 </view>
          </view>
        </template>
        <view class="btn" v-else-if="!currentOrderData?.isHasCurrentOrder && orders.length === 0">
          <view class="addres-info" v-if="!runing" @click="acceptOrdersHandler"> 开始接单 </view>
          <view class="addres-info" v-else @click="runningHandler"> 接单中 </view>
        </view>
        <template v-else>
          <view class="btn">
            <view class="addres-info" @click="showModal = true">
              接单中…{{ orders.length }}个
            </view>
          </view>
          <view class="btn">
            <view class="addres-info" @click="stopServiceHandler"> 结束接单 </view>
          </view>
        </template>
      </template>

      <view class="no-person" v-else>
        <view class="right">
          <view class="info">登录开始接单</view>
        </view>
        <view class="left">
          <view class="button" @click="loginHandler">立即登录</view>
        </view>
      </view>
    </view>

    <CustomModal
      v-model:visible="showModal"
      title="订单确认"
      content="您确定要接下这个订单吗？"
      confirmText="立刻抢单"
      cancelText="再想想"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      @close="handleClose"
      :showClose="true"
    >
      <!-- 也可以插入复杂内容 -->
      <view class="order-content">
        <view
          :class="{ checked: item.checked }"
          v-for="(item, index) in orders"
          :key="index"
          @click="clickHandler(item)"
        >
          <view class="order-item">
            <view class="label">订单编号：</view>
            <view class="value">{{ item.orderId }}</view>
          </view>
          <view class="order-item">
            <view class="label">起始点：</view>
            <view class="value">{{ item.startLocation }}</view>
          </view>
          <view class="order-item">
            <view class="label">结束点：</view>
            <view class="value">{{ item.endLocation }}</view>
          </view>
          <view class="order-item">
            <view class="label">预估金额：</view>
            <view class="value">{{ item.expectAmount }}</view>
          </view>
          <view class="order-item">
            <view class="label">预估里程：</view>
            <view class="value">{{ item.expectDistance }}</view>
          </view>
          <view class="order-item">
            <view class="label">下单时间：</view>
            <view class="value">{{ item.createTime }}</view>
          </view>
        </view>
      </view>
    </CustomModal>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100%;
  overflow: hidden;
}

.index-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $background-color;
  position: relative;

  .order-content {
    .checked {
      border: 1px solid #007aff;
    }
    .order-item {
      display: flex;
      flex-direction: row;
      margin-bottom: 10rpx;
      .label {
        text-align: right;
        width: 140rpx;
        white-space: nowrap;
      }
      .value {
        flex: 1;
      }
    }
  }

  .drawer {
    position: absolute;
    left: 60rpx;
    right: 60rpx;
    bottom: 80rpx;

    background-color: rgba(255, 255, 255, 0.95);
    border-top-left-radius: 16rpx;
    border-top-right-radius: 16rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    z-index: 10; // 浮在地图之上
    padding: 32rpx;
    box-sizing: border-box;

    display: flex;
    flex-direction: column;
    gap: 24rpx; // 子元素间距

    .top {
      display: flex;
      justify-content: space-around;
      font-size: 28rpx;
      color: #333;
      font-weight: 500;

      view {
        text-align: center;
      }
    }

    .bottom {
      font-size: 30rpx;
      color: #1a1a1a;
      line-height: 1.5;

      .addres-info {
        word-wrap: break-word;
        white-space: pre-wrap;
        text-align: center;
      }
    }

    .btn {
      padding: 20rpx 0;
      background-color: #007aff;
      color: white;
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      border-radius: 40rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
    }
  }

  .no-person {
    display: flex;
    align-items: center; // 垂直居中
    justify-content: space-between; // 左右两端对齐
    padding: 20rpx 40rpx; // 内边距，适合小程序
    background-color: #fff; // 背景浅灰，提升可读性
    border-radius: 20rpx; // 圆角
    margin: 20rpx; // 外边距

    .right {
      flex: 1; // 占据剩余空间
      display: flex;
      flex-direction: column; // 垂直排列标题和信息

      .title {
        font-size: $font-size;
        font-weight: 600;
        color: #343537;
        margin-bottom: 8rpx;

        // 如果 storeName 较长，可加省略号
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 400rpx;
      }

      .info {
        font-size: $font-mini-size;
        color: #666;
      }
    }

    .left {
      // 登录按钮容器，可加 margin 控制间距
      .button {
        padding: 0 32rpx;
        height: 40rpx;
        line-height: 40rpx;
        background-color: $color; // 主题色（如橙色）
        color: #fff;
        font-size: 18rpx;
        font-weight: 500;
        border-radius: 20rpx;
        text-align: center;
        min-width: 140rpx;
      }
    }
  }
}
</style>
